import router, { asyncRoutes, constantRoutes } from '@/router'
import store from '..'
import load from 'jszip/lib/load'



/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
    if (route.meta && route.meta.roles) {
        return roles.some(role => route.meta.roles.includes(role))
    } else {
        return true
    }
}

export const loadView = (view) => {
    return (resolve) => require([`@/views/${view}`], resolve)
}
export const loadLayoutView = (view) => {
    return (resolve) => require([`@/layout/index`], resolve)
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
    const res = []

    routes.forEach(route => {
        if (route.component) {
            const component = route.component
            if (typeof component === 'string') {
                if (component === 'Layout') {
                    route.component = loadLayoutView(component)
                } else {
                    route.component = loadView(component)
                }
            } else {
                //这里不能加载路由 让自己去   component: () => import('@/views/components-demo/markdown'),
                //否则报错 如果
            }
            //route.component = component => require(`@/views/${component}`)
        }
        const tmp = { ...route }
        if (hasPermission(roles, tmp)) {
            if (tmp.children) {
                tmp.children = filterAsyncRoutes(tmp.children, roles)
            }
            res.push(tmp)
        }
    })

    return res
}


const state = {
    routes: [],
    addRoutes: []
}

const mutations = {
    SET_ROUTES: (state, routes) => {
        state.addRoutes = routes
        state.routes = constantRoutes.concat(routes)
    }
}

const actions = {
    generateRoutes({ commit }, roles) {
        return new Promise(resolve => {
            let accessedRoutes

            //把 后端请求到的 菜单获取出来 
            let menus = store.getters.menus

            //accessedRoutes = asyncRoutes || []
            accessedRoutes = [
             
            ]
            
            menus = menus.concat(accessedRoutes);
            //核心 提交到 filterAsyncRoutes 方法中 动态加载菜单路由 
            menus = filterAsyncRoutes(menus, roles)
            commit('SET_ROUTES', menus)
            resolve(menus)
        })
    }
}



export default {
    namespaced: true,
    state,
    mutations,
    actions
}
